package cn.iocoder.yudao.module.pmp.service.project;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.business.vo.business.CrmBusinessTransferReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.permission.vo.CrmPermissionSaveReqVO;
import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.crm.enums.permission.CrmPermissionLevelEnum;
import cn.iocoder.yudao.module.crm.framework.permission.core.annotations.CrmPermission;
import cn.iocoder.yudao.module.crm.service.permission.CrmPermissionService;
import cn.iocoder.yudao.module.crm.service.permission.bo.CrmPermissionCreateReqBO;
import cn.iocoder.yudao.module.crm.service.permission.bo.CrmPermissionTransferReqBO;
import cn.iocoder.yudao.module.pmp.controller.admin.project.vo.ProjectPageReqVO;
import cn.iocoder.yudao.module.pmp.controller.admin.project.vo.ProjectSaveReqVO;
import cn.iocoder.yudao.module.pmp.dal.dataobject.project.ProjectDO;
import cn.iocoder.yudao.module.pmp.dal.mysql.project.ProjectMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.crm.enums.LogRecordConstants.*;

/**
 * 项目登记 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, ProjectDO> implements ProjectService {

    @Resource
    private ProjectMapper projectMapper;


    @Resource
    private CrmPermissionService crmPermissionService;

    @LogRecord(type = MOA_PROJECT_TYPE, subType = MOA_PROJECT_CREATE_SUB_TYPE, bizNo = "{{#project.id}}",
            success = MOA_PROJECT_CREATE_SUCCESS)
    @Override
    public Long createProject(ProjectSaveReqVO createReqVO) {
        // 插入
        ProjectDO project = BeanUtils.toBean(createReqVO, ProjectDO.class);
        if (project.getOwnerUserId() == null) {
            project.setOwnerUserId(getLoginUserId());
        }
        projectMapper.insert(project);
        CrmPermissionSaveReqVO crmPermissionSaveReqVO = new CrmPermissionSaveReqVO();
        crmPermissionSaveReqVO.setLevel(CrmPermissionLevelEnum.OWNER.getLevel());
        crmPermissionSaveReqVO.setBizId(project.getId());
        crmPermissionSaveReqVO.setBizType(CrmBizTypeEnum.CRM_RECEIVABLE_PMP.getType());
        crmPermissionSaveReqVO.setUserId(project.getOwnerUserId());

        // 3. 创建数据权限
        crmPermissionService.createPermission(new CrmPermissionCreateReqBO().setUserId(project.getOwnerUserId())
                .setBizType(CrmBizTypeEnum.CRM_RECEIVABLE_PMP.getType()).setBizId(project.getId())
                .setLevel(CrmPermissionLevelEnum.OWNER.getLevel()));


        LogRecordContext.putVariable("project", project);

        return project.getId();
    }

    @Override
    @LogRecord(type = MOA_PROJECT_TYPE, subType = MOA_PROJECT_UPDATE_SUB_TYPE, bizNo = "{{#project.id}}",
            success = MOA_PROJECT_UPDATE_SUCCESS)
    public void updateProject(ProjectSaveReqVO updateReqVO) {
        // 校验存在
        validateProjectExists(updateReqVO.getId());
        // 更新
        ProjectDO updateObj = BeanUtils.toBean(updateReqVO, ProjectDO.class);
        projectMapper.updateById(updateObj);
        LogRecordContext.putVariable("project", updateObj);

    }

    @Override
    public void deleteProject(Long id) {
        // 校验存在
        validateProjectExists(id);
        // 删除
        projectMapper.deleteById(id);
    }

    private void validateProjectExists(Long id) {
        if (projectMapper.selectById(id) == null) {
            throw new ServiceException(500, "项目登记不存在");
        }
    }

    @Override
    public ProjectDO getProject(Long id) {
        return projectMapper.selectById(id);
    }

    @Override
    public PageResult<ProjectDO> getProjectPage(ProjectPageReqVO pageReqVO, Long userId) {

        return projectMapper.selectPage(pageReqVO, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = MOA_PROJECT_TYPE, subType = MOA_PROJECT_TRANSFER_SUB_TYPE, bizNo = "{{#reqVO.id}}",
            success = MOA_PROJECT_TRANSFER_SUCCESS)
    @CrmPermission(bizType = CrmBizTypeEnum.CRM_RECEIVABLE_PMP, bizId = "#reqVO.id", level = CrmPermissionLevelEnum.OWNER)
    public void transferProject(CrmBusinessTransferReqVO reqVO, Long userId) {
        ProjectDO projectDO = validateBusinessExists(reqVO.getId());
        // 2.1 数据权限转移
        crmPermissionService.transferPermission(new CrmPermissionTransferReqBO(userId, CrmBizTypeEnum.CRM_RECEIVABLE_PMP.getType(),
                reqVO.getId(), reqVO.getNewOwnerUserId(), reqVO.getOldOwnerPermissionLevel()));
        // 2.2 设置新的负责人
        projectMapper.updateOwnerUserIdById(reqVO.getId(), reqVO.getNewOwnerUserId());

        // 记录操作日志上下文
        LogRecordContext.putVariable("project", projectDO);
    }

    private ProjectDO validateBusinessExists(Long id) {
        ProjectDO projectDO = projectMapper.selectById(id);
        return projectDO;
    }

}
